package server.handle;

import error.RemoteMethodNotFoundException;
import factory.ProxyFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import support.RpcContext;
import support.RpcInfo;
import util.AgentInvorker;

import java.lang.reflect.Method;
import java.nio.channels.SocketChannel;

//接受远程调用请求，数据入站处理器
public class DataInboundHandle extends SimpleChannelInboundHandler<RpcInfo> {

    static Logger logger = LoggerFactory.getLogger(DataInboundHandle.class);

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("新的连接到来");
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        RpcContext.addConnect(channel);
        super.channelRegistered(ctx);
    }

    //处理客户端发送过来的调用请求
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcInfo msg) throws Exception {
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        try {
            Method callMethod = RpcContext.findCallMethod(msg);
            RpcInfo invoke = AgentInvorker.invoke(callMethod, msg);
            channel.writeAndFlush(invoke);
        }catch (RemoteMethodNotFoundException e){
            e.printStackTrace();
            RpcInfo errRes =new RpcInfo();
            errRes.setErrorCode(e.getMessage());
            channel.writeAndFlush(errRes);
        }
    }

}
